package net.dgg.dggcloud.service.jrcrm.aspect;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.entity.Role;
import net.dgg.dggcloud.service.entity.menu.MenuEntity;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.iboss.constant.SysRecordConstant;
import net.dgg.dggcloud.service.jrcrm.constant.OpreateEnum;
import net.dgg.dggcloud.service.jrcrm.constant.OpreateTypeEnum;
import net.dgg.dggcloud.service.jrcrm.service.log.SysModifyAuthRecordService;
import net.dgg.dggcloud.service.jrcrm.utils.IpUtil;
import net.dgg.dggcloud.service.service.MenuService;
import net.dgg.dggcloud.service.service.RoleService;
import net.dgg.framework.tac.mq.rabbitmq.queue.DggMessageSendUtil;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;

/**
 * 保存角色aop
 * 
 * @Title: RoleAuthSaveAspect
 * @Description:
 * @Auther: 雷力
 * @Date: 2018-11-28 12:09:43
 *
 */
@Aspect
@Component
public class RoleAuthSaveAspect {
	private Logger logger = Logger.getLogger(RoleAuthSaveAspect.class);

	@Autowired
	private RoleService roleService;
	@Autowired
	private MenuService menuService;

	@Pointcut("execution(public * net.dgg.dggcloud.platform.action.RoleController.authSave(..))")
	public void webLog() {
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Before("webLog()")
	public void before(JoinPoint jp) {
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		User user = SessionManager.getCurrentUser();
		Object[] objs = jp.getArgs();
		Long roleId = Long.valueOf(objs[2].toString());
		Role role = roleService.find4Id(roleId);

		Map record = new HashMap<>();
		record.put("ip", IpUtil.getIPAddress(request));
		record.put("opreate", OpreateEnum.ROLEMUNE.getOpreate());
		record.put("opreateTime", DateUtil.dateToString(new Date()));
		record.put("userLoginname", user.getLoginName());
		record.put("userName", user.getName());
		record.put("vuserLoginname", role.getRoleKey());
		record.put("vuserName", role.getName());
		record.put("clazz", SysModifyAuthRecordService.class);

		List<Long> olds = new ArrayList<>();

		Iterator<Map> imap = roleService.findMenuIdsByRoleId(roleId).iterator();
		while (imap.hasNext()) {
			Map map = imap.next();
			olds.add(Long.valueOf(map.get("menuid").toString()));
		}
		Long[] longs = objs[1] == null ? new Long[0] : (Long[]) objs[1];
		List<Long> news = new ArrayList<>(Arrays.asList(longs));
		List<Long> temps = new ArrayList<>();
		temps.addAll(olds);
		olds.removeAll(news);
		news.removeAll(temps);

		if (!olds.isEmpty()) {// 删除
			String strolds = StringUtils.join(olds, ",");
			List<MenuEntity> menus = menuService.findCodeAndName4Ids(strolds);
			record.put("id", DggKeyWorker.nextId());
			record.put("opreateType", OpreateTypeEnum.DELETE.getType());
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			Iterator<MenuEntity> iterator = menus.iterator();
			while (iterator.hasNext()) {
				MenuEntity menu = iterator.next();
				sb.append(menu.getId() + ":" + menu.getName() + ",");
			}
			sb.deleteCharAt(sb.length() - 1);
			sb.append("}");
			record.put("modifyContent", sb.toString());
			logger.info("======================>发送消息...");
			DggMessageSendUtil.putMessage(SysRecordConstant.QUEUENAME, record);
		}
		if (!news.isEmpty()) {// 添加
			String strnews = StringUtils.join(news, ",");
			List<MenuEntity> menus = menuService.findCodeAndName4Ids(strnews);
			record.put("id", DggKeyWorker.nextId());
			record.put("opreateType", OpreateTypeEnum.ADD.getType());
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			Iterator<MenuEntity> iterator = menus.iterator();
			while (iterator.hasNext()) {
				MenuEntity menu = iterator.next();
				sb.append(menu.getId() + ":" + menu.getName() + ",");
			}
			sb.deleteCharAt(sb.length() - 1);
			sb.append("}");
			record.put("modifyContent", sb.toString());
			logger.info("======================>发送消息...");
			DggMessageSendUtil.putMessage(SysRecordConstant.QUEUENAME, record);
		}
	}
}
